package com.finley.flowabledemo.design.state.demo02.state;


import com.finley.flowabledemo.design.state.demo02.source.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @description:
 * @author: xianfei.chao
 * @date 2025/6/24 13:35
 * @version: 1.0
 */
public class SourceCode {

    public static void main(String[] args) {
        Order order = new Order();
        ArrayList<OrderItem> orderItems = new ArrayList<>();
        orderItems.add(new OrderItem("1001", 2));
        orderItems.add(new OrderItem("1002", 3));
        orderItems.add(new OrderItem("1003", 4));
        order.setItems(orderItems);
        order.setId(100001L);
        order.setStatus(OrderStatus.NEW.getCode());
        order.setCustomerEmail("1499022767@qq.com");
        order.setPaymentDetails(orderItems);
        order.setTotalAmount(200.0D);
        // 执行语句
        processOrder(order);
    }

    public static void processOrder(Order order) {
        validateOrder(order);
        OrderStatusContext context = constructStatusContext(order);
        // new 状态
        ProcessingStatueState statueState = new ProcessingStatueState();
        statueState.handle(context);

        // PROCESSING 状态
        context.getOrder().setStatus(OrderStatus.PROCESSING.getCode());
        statueState.handle(context);

        // PAID 状态
        context.getOrder().setStatus(OrderStatus.PAID.getCode());
        statueState.handle(context);

        // shipped 状态
        context.getOrder().setStatus(OrderStatus.SHIPPED.getCode());
        statueState.handle(context);
    }

    private static OrderStatusContext constructStatusContext(Order order) {
        OrderStatusContext context = new OrderStatusContext();
        context.setOrder(order);
        DatabaseConnection2 conn = new DatabaseConnection2("jdbc:mysql://localhost/shop", "root", "password");
        context.setConn(conn);
        context.setEmailSender(new EmailSender());
        return context;
    }

    private static void validateOrder(Order order) {
        if (Objects.isNull(order)) {
            throw new RuntimeException("order is null");
        }
        if (!Objects.equals(order.getStatus(), OrderStatus.NEW.getCode())) {
            throw new RuntimeException("order status ne new");
        }
        if (order.getTotalAmount() < 0) {
            throw new RuntimeException("order totalAmount lt zero");
        }
        checkInventory(order.getItems());
    }

    private static boolean checkInventory(List<OrderItem> items) {
        return true;
    }
}
